class EditorArticlesController < ApplicationController
  before_filter :authenticate
  layout "editor"
    
  # GET /articles
  # GET /articles.xml
  def index
    raise Exceptions::UserAccessError if !current_user.isRole?(Role.find_by_alias('EDITOR'))
    
    @filter = params[:filter].nil? ? {} : params[:filter]
    # @page = params[:page].nil? ? nil : params[:page]
    @articles = Article.articles_status_table(@filter).paginate :page=>params[:page], :order=>'created_at desc', :per_page => 5
    # @articles = Article.all.paginate :page=>(params[:page].to_i - 1), :order=>'created_at desc', :per_page => 3 if @articles.count == 0 && !params[:page].nil?
    # @users = User.all
    # @article_statuses = ArticleStatus.all
    @articles_approving = Article.articles_approving
    @articles_new = Article.articles_new
    
    @article_statuses = ArticleStatus.all
    @users = User.all
    
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @articles }
      format.js { render '_articles.js.erb' }
    end
  end
  
  def activities_table   
    @articles_approving = Article.articles_approving
    # @articles_new = Article.articles_new
  end
  
  def approve
    raise Exceptions::UserAccessError if !current_user.isRole?(Role.find_by_alias('EDITOR'))
    
    begin
      @article = Article.find(params[:id])
    rescue ActiveRecord::RecordNotFound      
      return nil
    end
    
    # right bar
    @articles_approving = Article.articles_approving
    @articles_new = Article.articles_new

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @article }
    end
  end
  
  def approving
    raise Exceptions::UserAccessError if !current_user.isRole?(Role.find_by_alias('EDITOR'))
    
    @article_approval = ArticleApproval.new(params[:article_approval])
    
    if @article_approval[:status] == 'non'
      flash[:error] = 'Must select an approving action.!!!'
      redirect_to(url_for({:action => "approve", :id => params[:article_id]}))
      return nil
    end
    
    @article = Article.find(params[:article_id])
    @article_approval.article = @article
    @article_approval.user = current_user
    
    @article.article_status = ArticleStatus.get(@article_approval.status)
    
    respond_to do |format|
      if @article_approval.save && @article.save
        format.html { redirect_to(url_for({:action => "index"}), :notice => 'Approving successfully.') }     
      end
    end
  end
  
end
